package org.xx.armory.spring5.mvc.converters;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;

import java.util.Set;

import static org.xx.armory.commons.StringConverter.parseBoolean;

public class StringToBooleanConverter
        implements GenericConverter {
    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Set.of(
                new ConvertiblePair(String.class, Boolean.class),
                new ConvertiblePair(String.class, boolean.class)
        );
    }

    @Override
    public Object convert(
            Object source,
            TypeDescriptor sourceType,
            TypeDescriptor targetType
    ) {
        final var s = source != null ? source.toString().strip() : "";
        final var type = targetType.getType();

        if (type.equals(Boolean.class)) {
            return parseBoolean(s, null);
        } else if (type.equals(boolean.class)) {
            return parseBoolean(s, false);
        } else {
            assert false : "Illegal target type: " + targetType;
            return null;
        }
    }
}
